package com.example.zwlyz;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.zwlyz.adapters.AccountListAdapter;
import com.example.zwlyz.models.Account;

import java.util.List;

public class AccountManagementActivity extends AppCompatActivity {

    private ListView listView;
    private AccountListAdapter accountAdapter;
    private List<Account> accounts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_management);

        listView = findViewById(R.id.listView);
        accounts = AccountManager.getAllAccounts();

        if (accounts != null && !accounts.isEmpty()) {
            accountAdapter = new AccountListAdapter(this, accounts);
            listView.setAdapter(accountAdapter);

            // 短按跳转到修改密码界面
            listView.setOnItemClickListener((parent, view, position, id) -> {
                Account account = accounts.get(position);
                Intent intent = new Intent(AccountManagementActivity.this, ChangePasswordActivity.class);
                intent.putExtra("accountId", account.getId());
                startActivity(intent);
            });

            // 长按删除账号
            listView.setOnItemLongClickListener((parent, view, position, id) -> {
                Account account = accounts.get(position);
                AccountManager.deleteAccount(account.getId());
                accounts = AccountManager.getAllAccounts();
                accountAdapter = new AccountListAdapter(AccountManagementActivity.this, accounts);
                listView.setAdapter(accountAdapter);
                Toast.makeText(AccountManagementActivity.this, "账号已删除", Toast.LENGTH_SHORT).show();
                return true;
            });
        } else {
            Toast.makeText(this, "没有账号数据", Toast.LENGTH_SHORT).show();
        }

        // 添加账号按钮
        findViewById(R.id.btnAddAccount).setOnClickListener(v -> {
            startActivity(new Intent(AccountManagementActivity.this, RegisterActivity.class));
        });
    }
}